package com.hyt.it.ogt.ks.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName BlockedThreadPoolExecutor.java
 * @author admin
 * @version 1.0.0
 * @Description 阻塞式线程池
 */
@Slf4j
public class ClearInitCandidateDataThreadPoolExecutor extends ThreadPoolExecutor {
    //锁
    private ReentrantLock pauseLock = new ReentrantLock();
    //入场卷
    private Condition unpaused = pauseLock.newCondition();

    /**
     * 构造方法，当需要控制更加多参数时，可以重载
     * @param corePoolSize
     * @param maximumPoolSize
     * @param maxQueueSize
     */
    public ClearInitCandidateDataThreadPoolExecutor(int corePoolSize, int maximumPoolSize, int maxQueueSize){
        super(corePoolSize, maximumPoolSize, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(maxQueueSize, Boolean.TRUE), r -> {
            Thread t = new Thread(r);
            t.setName("阻塞式线程池" + t.getId());
            return t;
        });
    }

    @Override
    public void execute(Runnable job){
        pauseLock.lock();
        try {
            //当池中运行的线程数与最大的线程数相当
            while(getPoolSize() == getMaximumPoolSize() && 1 != getMaximumPoolSize()){
                unpaused.await();
            }
            super.execute(job);
        } catch (Exception e){
            log.error("阻塞式线程池有任务异常:",e);
        } finally {
            pauseLock.unlock();
        }
    }

    @Override
    public void afterExecute(Runnable job,Throwable t){
        super.afterExecute(job,t);
        try {
            pauseLock.lock();
            unpaused.signal();
        } finally {
            pauseLock.unlock();
        }
    }

    //判断是否还有任务在队表中阻塞
    public Boolean isQueueEmpty(){
        return getQueue().size() == 0;
    }
}
